import React, { useState } from 'react';
import { diagnoseApiIssue } from '../services/apiDiagnostics';

function ApiDiagnosticTool() {
  const [diagnosticResult, setDiagnosticResult] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showDetails, setShowDetails] = useState(false);

  const runDiagnostics = async () => {
    setIsLoading(true);
    try {
      const result = await diagnoseApiIssue();
      setDiagnosticResult(result);
    } catch (error) {
      setDiagnosticResult({
        status: 'error',
        message: `诊断过程出错: ${error.message}`,
        error
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="api-diagnostic-tool">
      <h3>API连接诊断</h3>
      
      <button
        type="button"
        onClick={runDiagnostics}
        disabled={isLoading}
        className="btn-secondary"
      >
        {isLoading ? '诊断中...' : '诊断API连接'}
      </button>
      
      {diagnosticResult && (
        <div className={`diagnostic-result ${diagnosticResult.status === 'ok' ? 'success' : 'error'}`}>
          <p className="result-message">{diagnosticResult.message}</p>
          
          <button
            type="button"
            onClick={() => setShowDetails(!showDetails)}
            className="btn-link"
          >
            {showDetails ? '隐藏详情' : '显示详情'}
          </button>
          
          {showDetails && (
            <pre className="diagnostic-details">
              {JSON.stringify(diagnosticResult, null, 2)}
            </pre>
          )}
        </div>
      )}
    </div>
  );
}

export default ApiDiagnosticTool;
